//app.js
const api = require("./config/api");
const util = require("./utils/util");

App({
  onLaunch: function () {
    let that = this;

    // 直接在onShow里做这个吧
    // wx.checkSession({
    //   success: () => {
    //     if (!that.globalData.teacherInfo.length > 0 && !that.globalData.parentInfo.length > 0) {
    //       let openid = wx.getStorageSync('openid');
    //       if (openid != null && openid != '') {
    //         that.queryUserInfoWithOpenId(openid);
    //       } else {
    //         that.login();
    //       }
    //     } else {
    //       this.loginCall();
    //     }
    //   },
    //   fail: () => {
    //     that.login();
    //   }
    // })

    // 获取系统状态栏信息
    wx.getSystemInfo({
      success: e => {
        this.globalData.StatusBar = e.statusBarHeight;
        this.globalData.screenHeight = e.screenHeight;
        this.globalData.windowHeight = e.windowHeight;
        let capsule = wx.getMenuButtonBoundingClientRect();
        if (capsule) {
          this.globalData.Custom = capsule;
          this.globalData.CustomBar = capsule.bottom + capsule.top - e.statusBarHeight;
        } else {
          this.globalData.CustomBar = e.statusBarHeight + 50;
        }
      }
    })
  },
  onShow: function () {
    let that = this;
    if (this.globalData.loadShow) {
      //企业微信可以先用这个获取environment，企业微信进入可以获取到，普通微信是undefined
      //应该要记录unionId记录统一性（企业用户微信打开时也能用）
      // wx.getSystemInfo({
      //   success: (res) => {
      //     console.log(res);
      //     console.log(res.environment);
      //   }
      // });
      wx.checkSession({
        //session_key 未过期，并且在本生命周期一直有效
        success: () => {
          let openid = wx.getStorageSync('openid');
          if (openid != null && openid != '') {
            if (!that.globalData.teacherInfo.length > 0 && !that.globalData.parentInfo.length > 0) {
              that.queryUserInfoWithOpenId(openid);
            } else {
              that.globalData.canIShow = true;
              that.loginCall();
            }
          } else {
            that.login();
          }
        },
        // session_key 已经失效，需要重新执行登录流程
        fail: () => {
          that.login();
        }
      })
    }
  },
  // 设置initTeacher和initParent状态
  setInitStatus(obj) {
    if (!obj.parentInfo.length > 0) {
      this.globalData.isInitParent = false;
    } else {
      this.globalData.isInitParent = true;
      this.globalData.userType = 2;
    }
    if (!obj.teacherInfo.length > 0) {
      this.globalData.isInitTeacher = false;
    } else {
      this.globalData.isInitTeacher = true;
      this.globalData.userType = 1;
    }
  },
  // 登录方法
  login() {
    wx.login({
      success: res => {
        wx.request({
          url: api.initUser,
          header: {
            'content-type': 'application/json',
            'xcx-token': this.xcxtoken
          },
          method: 'POST',
          data: {
            code: res.code
          },
          success: (res) => {
            if (res.data.code != '0') {
              wx.showToast({
                title: '服务器出错了，请联系管理员。',
                icon: 'none'
              })
              return null;
            }
            this.globalData.appUser = res.data.data;
            this.globalData.openid = res.data.data.openid;
            this.globalData.teacherInfo = res.data.data.teacherInfo;
            this.globalData.parentInfo = res.data.data.parentInfo;
            this.setInitStatus({
              teacherInfo: res.data.data.teacherInfo,
              parentInfo: res.data.data.parentInfo,
              appUser: res.data.data,
            })
            this.globalData.canIShow = true;
            // 设置缓存
            wx.setStorage({
              key: "openid",
              data: res.data.data.openid
            });
            wx.setStorage({
              key: "session_key",
              data: res.data.data.session_key
            });
            this.CallBack();
          },
          fail: err => {
            wx.showToast({
              title: 'err.data.msg',
            })
            console.error(err)
          }
        })
      }
    })
  },
  queryUserInfoWithOpenId(openid) {
    let that = this;
    wx.request({
      url: api.getUserInfo,
      method: "POST",
      data: {
        openid: openid
      },
      header: {
        'content-type': 'application/json',
        'xcx-token': that.xcxtoken
      },
      success: res => {
        that.globalData.teacherInfo = res.data.data.teacherInfo;
        that.globalData.parentInfo = res.data.data.parentInfo;
        that.globalData.appUser = res.data.data;
        that.setInitStatus({
          teacherInfo: res.data.data.teacherInfo,
          parentInfo: res.data.data.parentInfo,
          appUser: res.data.data,
        })
        that.globalData.canIShow = true;
        that.CallBack();
      }
    })
  },

  CallBack() {
    if (!this.globalData.teacherInfo.length > 0 && !this.globalData.parentInfo.length > 0) {
      this.registerCall();
    } else {
      this.loginCall();
    }
  },


  // 跳转到注册页面
  registerCall() {
    if (this.registerCallback) {
      this.registerCallback();
    }
  },
  // 进入到index.js
  loginCall() {
    if (this.loginCallback) {
      this.loginCallback();
    }
  },
  globalData: {
    loadShow: true, // 默认会调用app.onShow（chooseImage、uploadFile之类的api都会调用show，太频繁了）
    canIShow: false,
    isInitTeacher: false, // 判断是否已注册老师
    isInitParent: false, // 判断是否已注册家长
    userType: 1, // 用户角色，默认老师
    switchTab: false, // 是否切换过tab页面
    appUser: null,
    teacherInfo: [],
    parentInfo: [], // 里面包含家长绑定孩子时的数据
    subjectArray: [], // 科目数组
    selectedClazz: null, // 选择的班级（首页左上角选择的）
    selectedGrade: null, // 选择的年纪（首页左上角选择的）
    teacherCharacter: {
      evaLeaderType: 0, // 0无权限，1总负责人，2板块负责人
      isLeader: false,  // 值周行政
      isHead: false,  // 组长
      isMember: false,  // 组员
    }, // 老师身份
    subjectEnglishNameMap: function () { // 科目英文名
      var map = new Map();
      map.set('语文', 'chinese');
      map.set('数学', 'math');
      map.set('英语', 'english');
      map.set('物理', 'physics');
      map.set('化学', 'chemistry');
      map.set('生物', 'biology');
      map.set('历史', 'history');
      map.set('地理', 'geography');
      map.set('政治', 'politics');
      map.set('科学', 'science');
      map.set('体育', 'sports');
      return map;
    }
  }
})